package vn.hung.data.graphs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.google.common.io.Closeables;
import com.google.common.io.Files;


public class EdgeListGraph extends Graph {
	
	private List<Edge> edgeList = new ArrayList<Edge>();
	public EdgeListGraph() {
		this.nodeCount = 0;
	}
	
	public EdgeListGraph(int nodeCount) {
		this.nodeCount = nodeCount;
	}
	
	public void addEdge(int x, int y) {
		edgeList.add(new Edge(x, y));
	}
	
	public void addEdge(int x, int y, int weight) {
		edgeList.add(new Edge(x, y, weight));
	}
	
	public void addEdge(int x, int y, float weight) {
		edgeList.add(new Edge(x, y, weight));
	}
	
	@Override
	public void buildGraphFromPath(String path, String delimiter) throws IOException {
		BufferedReader reader = Files.newReader(new File(path), Charset.forName("UTF-8"));
		String line = "";
		int lineCount = 0;
		// graph file format: fist line is the number of nodes
		// following lines consist of edge defined by two end points and, possibly, its weight
		while ((line = reader.readLine()) != null) {
			lineCount ++;
			if (lineCount == 1) {
				nodeCount = Integer.parseInt(line);
			} else {
				String[] chunks = line.split(delimiter);
				if (chunks.length == 2) {
					int x = Integer.parseInt(chunks[0]);
					int y = Integer.parseInt(chunks[1]);
					addEdge(x, y);
				} else if (chunks.length == 3) {
					int x = Integer.parseInt(chunks[0]);
					int y = Integer.parseInt(chunks[1]);
					// check whether weight is float or integer
					if (chunks[2].contains(".")) {
						float weight = Float.parseFloat(chunks[2]);
						addEdge(x, y, weight);
					} else {
						int weight = Integer.parseInt(chunks[2]);
						addEdge(x, y, weight);
					}
				} else {
					throw new IOException("Invalid file input file format!");
				}
			}
		}
		Closeables.closeQuietly(reader);
	}

	@Override
	public void writeGraphToPath(String path, String delimiter) throws IOException {
		BufferedWriter writer = Files.newWriter(new File(path), Charset.forName("UTF-8"));
		writer.write(nodeCount + "\n");
		for (Edge edge: edgeList) {
			writer.write(edge.toString(delimiter));
		}
		Closeables.closeQuietly(writer);
	}
	
	
}



